package cn.ulegal.xudy.Service.serviceimpl;

import cn.ulegal.xudy.Dao.TestDao;
import cn.ulegal.xudy.Service.TestService;
import cn.ulegal.xudy.entity.CopyRightsVo;
import cn.ulegal.xudy.entity.TestModel;
import cn.ulegal.xudy.util.UlegalZCUtil;
//import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Ulegal on 2017/8/18.
 */
@Service
public class TestServiceImpl implements TestService {

   @Autowired
   TestDao testDao;

    @Override
    public Integer saveOidInfo(TestModel model) {

      Integer count = testDao.saveOidInfo(model);
        CopyRightsVo copyRightsVo = new CopyRightsVo();
        // 生成pdf
        tranPdf(copyRightsVo);
//邮件发送
        Boolean sendResult = UlegalZCUtil.sendEmail();
//     String tt =   getHashValue("");
//        System.out.println("----------"+tt);
        return null;
    }


    /**
     * 根据项目地址计算文件hash值
     * @param path
     * @return
     */
    private String getHashValue(String path) {
        String rootPath = UlegalZCUtil.rootPath();
        String filePath = rootPath + File.separator + "pdf" + File.separator + "templateOL.pdf";
        String hashValue = "";
        try {
            hashValue = UlegalZCUtil.getSHA256Checksum(filePath);
            File file = new File(filePath);
            if (file.exists()) {
//                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hashValue;
    }

    // pdf文件
    private Boolean tranPdf(CopyRightsVo copyRightsVo) {
        String filePath = UlegalZCUtil.rootPath() + File.separator + "pdf" + File.separator + "template.pdf";
        String toPath = UlegalZCUtil.rootPath() + File.separator + "pdf" + File.separator + "templateOL" + ".pdf";
        try {
            System.out.println(filePath);
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(filePath), new PdfWriter(toPath));
            PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(pdfDoc, true);
            pdfAcroForm.getField("fileName").setValue("小编");
            pdfAcroForm.getField("applicant").setValue("ol");
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
            String cmmitTime = simpleDateFormat.format(date);
            pdfAcroForm.getField("time").setValue(cmmitTime);
//            pdfAcroForm.getField("hashValue").setValue(copyRightsVo.getHashValue());
            pdfAcroForm.flattenFields();
            pdfDoc.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }





}
